package com.forum.service.impl;

import com.forum.constant.MessageConstant;
import com.forum.entity.Categories;
import com.forum.exception.CategoriesNameExists;
import com.forum.exception.DeletionNotAllowedException;
import com.forum.mapper.CategoriesMapper;
import com.forum.mapper.ThreadsMapper;
import com.forum.service.CategoriesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoriesServiceImpl implements CategoriesService {
    @Autowired
    private CategoriesMapper categoryMapper;

    @Autowired
    private ThreadsMapper threadsMapper;
    @Override
    public List<Categories> queryCategories() {
        return categoryMapper.queryCategories();
    }

    @Override
    public void update(Categories category) {
        categoryMapper.update(category);
    }

    @Override
    public void delete(Long id) {
        Long count = threadsMapper.queryByCategoryId(id);
        // 1.先判断列表是否被帖子使用
        if (count > 0){
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_EXCEPTION);
        }
        // 2.没使用则安心的删除
        categoryMapper.deleteById(id);
    }

    @Override
    public void insert(Categories category) {
        String name = category.getName();
        Categories categories = categoryMapper.queryByName(name);
        if (categories != null) {
            throw new CategoriesNameExists(MessageConstant.EXISTS);
        }
        // 不存在，则添加
        categoryMapper.insert(category);
    }


}
